package com.moyun.modelclass.activity;

import static com.moyun.modelclass.activity.MainActivity.unreadMsgSet;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.BottomPopupView;
import com.moyun.modelclass.dialog.ScanImageDialog;
import com.moyun.modelclass.event.LoginStateEvent;
import com.moyun.modelclass.frank.FActivity;
import com.moyun.modelclass.frank.HeartBeatRequest;
import com.moyun.modelclass.frank.MultiAdapter;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.ChatGetApi;
import com.moyun.modelclass.http.api.ChatOpenApi;
import com.moyun.modelclass.http.api.ChatSendApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.databinding.ActivityChatDetailBinding;
import com.moyun.modelclass.databinding.ItemChatDetialLeftBinding;
import com.moyun.modelclass.databinding.ItemChatDetialRightBinding;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.DataUtil;
import com.moyun.modelclass.utils.GlideEngine;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ChatDetailActivity extends FActivity<ActivityChatDetailBinding> {

    private static final String TAG = "ChatDetailActivity";
    private MultiAdapter adapter;

    public static void start(Context context, String userId) {
        Intent starter = new Intent(context, ChatDetailActivity.class);
        starter.putExtra("userId", userId);
        context.startActivity(starter);
    }

    public static void start(Context context, String userId, String phoneNum) {
        Intent starter = new Intent(context, ChatDetailActivity.class);
        starter.putExtra("userId", userId);
        starter.putExtra("phoneNum", phoneNum);
        context.startActivity(starter);
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void initView() {
        super.initView();
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData(true);
            }
        });
        adapter = new MultiAdapter() {
            @Override
            protected ViewBindingHolder createViewBindingHolder(@NonNull ViewGroup parent, int viewType) {
                if (viewType == 1) {
                    return new ViewBindingHolder<ItemChatDetialLeftBinding, ChatGetApi.Chats>(parent) {
                        @Override
                        public void onBindData(ChatGetApi.Chats bean, int position) {
                            super.onBindData(bean, position);
                            String sendTime = bean.sendTime;
                            if (canCheckInfo) {
                                binding.leftimage.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        UserInfoActivity.start(mActivity, userId);
                                    }
                                });
                            } else {
                                binding.leftimage.setOnClickListener(null);
                            }
                            binding.time.setText(DataUtil.getTimeShowString(TimeUtils.string2Millis(sendTime), false));
                            String url = getImageUrl(userId);
                            Glide.with(mActivity)
                                    .asBitmap()
                                    .load(CommonConfiguration.splitResUrl(3, url))
                                    .placeholder(R.drawable.icon_head_portrait)
                                    .error(R.drawable.icon_head_portrait)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                    .into(new BitmapImageViewTarget(binding.leftimage) {
                                        @Override
                                        protected void setResource(Bitmap resource) {
                                            super.setResource(resource);
                                            binding.leftimage.setImageBitmap(ImageUtils.toRound(resource));
                                        }
                                    });
                            String content = bean.content;
                            if (content.startsWith("[image") || content.startsWith("image/")) {
                                if (content.startsWith("[image")) {
                                    content = content.substring(7, content.length() - 1);
                                }
                                binding.leftText.setVisibility(View.GONE);
                                binding.leftContentImage.setVisibility(View.VISIBLE);
                                Glide.with(mActivity)
                                        .asBitmap()
                                        .load(CommonConfiguration.splitResUrl(3, content))
                                        .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                        .into(new BitmapImageViewTarget(binding.leftContentImage) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                super.setResource(resource);
                                                binding.leftContentImage.setImageBitmap(resource);
                                            }
                                        });
                                String finalContent = CommonConfiguration.splitResUrl(3, content);
                                binding.leftContentImage.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        ScanImageDialog.getInstance(mActivity, finalContent).builder().setNegativeButton().show();
                                    }
                                });
                            } else {
                                binding.leftText.setVisibility(View.VISIBLE);
                                binding.leftContentImage.setVisibility(View.GONE);
                            }
                        }
                    };
                } else if (viewType == 2) {
                    return new ViewBindingHolder<ItemChatDetialRightBinding, ChatGetApi.Chats>(parent) {
                        @Override
                        public void onBindData(ChatGetApi.Chats bean, int position) {
                            super.onBindData(bean, position);
                            String sendTime = bean.sendTime;
                            binding.time.setText(DataUtil.getTimeShowString(TimeUtils.string2Millis(sendTime), false));
                            String url = getImageUrl(bean.fromUserId);
                            Glide.with(mActivity)
                                    .asBitmap()
                                    .load(CommonConfiguration.splitResUrl(3, url))
                                    .placeholder(R.drawable.icon_head_portrait)
                                    .error(R.drawable.icon_head_portrait)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                    .into(new BitmapImageViewTarget(binding.rightimage) {
                                        @Override
                                        protected void setResource(Bitmap resource) {
                                            super.setResource(resource);
                                            binding.rightimage.setImageBitmap(ImageUtils.toRound(resource));
                                        }
                                    });
                            String content = bean.content;
                            if (content.startsWith("[image") || content.startsWith("image/")) {
                                if (content.startsWith("[image")) {
                                    content = content.substring(7, content.length() - 1);
                                }
                                binding.rightText.setVisibility(View.GONE);
                                binding.rightContentImage.setVisibility(View.VISIBLE);
                                Glide.with(mActivity)
                                        .asBitmap()
                                        .load(CommonConfiguration.splitResUrl(3, content))
                                        .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                        .into(new BitmapImageViewTarget(binding.rightContentImage) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                super.setResource(resource);
                                                binding.rightContentImage.setImageBitmap(resource);
                                            }
                                        });
                                String finalContent = CommonConfiguration.splitResUrl(3, content);
                                binding.rightContentImage.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        ScanImageDialog.getInstance(mActivity, finalContent).builder().setNegativeButton().show();
                                    }
                                });
                            } else {
                                binding.rightText.setVisibility(View.VISIBLE);
                                binding.rightContentImage.setVisibility(View.GONE);
                            }
                        }
                    };
                }
                return null;
            }

            @Override
            protected int getItemViewType(int position, Object o) {
                if (o instanceof ChatGetApi.Chats) {
                    ChatGetApi.Chats bean = (ChatGetApi.Chats) o;
                    if (bean.fromUserId.equals(userId)) {
                        return 1;
                    } else {
                        return 2;
                    }
                }
                return 0;
            }
        };
        mBinding.recyclerView.setAdapter(adapter);
    }

    private String getImageUrl(String userId) {
        if (TextUtils.isEmpty(userId)) {
            return "";
        }
        if (data == null) {
            return "";
        }
        if (data.fromUser.userId.equals(userId)) {
            return data.fromUser.avatar;
        } else {
            return data.receiveUser.avatar;
        }
    }

    String userId;
    String phoneNum;
    boolean canCheckInfo = false;
    @Override
    protected void initData() {
        super.initData();
        userId = getIntent().getStringExtra("userId");
        phoneNum = getIntent().getStringExtra("phoneNum");
        if (TextUtils.isEmpty(phoneNum)) {
            mBinding.ivPhone.setVisibility(View.GONE);
        } else {
            mBinding.ivPhone.setVisibility(View.VISIBLE);
            mBinding.ivPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showBottomPop();
                }
            });
        }
        unreadMsgSet.remove(userId);
        Log.i(TAG, "initData: " + userId);
        Log.i(TAG, "initData: " + unreadMsgSet);
        EasyHttp.post(this)
                .api(new ChatOpenApi().setReceiveUserId(userId))
                .request(new HttpCallback<HttpData<ChatOpenApi.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<ChatOpenApi.Bean> result) {
                        Log.d(TAG, "onSucceed() called with: result = [" + result + "]");
                        ChatOpenApi.Bean data = result.getData();
                        if (data == null) {
                            return;
                        }
                        if (data.canChat) {
                            mBinding.inputPanel.setVisibility(View.VISIBLE);
                            mBinding.noChat.setVisibility(View.GONE);
                        } else {
                            mBinding.inputPanel.setVisibility(View.GONE);
                            mBinding.noChat.setVisibility(View.VISIBLE);
                        }
                        phoneNum = data.phone;
                        canCheckInfo = data.canCheckInfo;
                        if (TextUtils.isEmpty(phoneNum)) {
                            mBinding.ivPhone.setVisibility(View.GONE);
                        } else {
                            mBinding.ivPhone.setVisibility(View.VISIBLE);
                            mBinding.ivPhone.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    showBottomPop();
                                }
                            });
                        }
                        ChatOpenApi.Bean.UserInfoVO userInfoVO = data.userInfoVO;
                        if (userInfoVO == null) {
                            finish();
                            return;
                        }
                        mBinding.name.setText(userInfoVO.nickName);
                        getData(true);
                    }
                });


    }

    private void showBottomPop() {
        BasePopupView popupView = new BottomPopupView(mActivity) {
            @Override
            protected int getImplLayoutId() {
                return R.layout.pop_chat_phone;
            }

            @Override
            protected void onCreate() {
                ((TextView) findViewById(R.id.phone)).setText(phoneNum);
                findViewById(R.id.dismiss).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setAction(intent.ACTION_DIAL); //调用拨号面板
                        intent.setData(Uri.parse("tel:" + phoneNum)); //设置要拨打的号码
                        startActivity(intent);
                        dismiss();
                    }
                });
            }
        };
        new XPopup.Builder(mActivity).asCustom(popupView).show();
    }

    ChatGetApi.Bean data;
    String lastId = "";

    private void getData(boolean refresh) {
        if (refresh) {
            lastId = "";
        }
        EasyHttp.post(this).api(new ChatGetApi().setLastId(lastId).setPageSize(100).setReceiveUserId(userId))
                .request(new HttpCallback<HttpData<ChatGetApi.Bean>>(null) {
                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        mBinding.refreshLayout.finishLoadMore();
                        mBinding.refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onSucceed(HttpData<ChatGetApi.Bean> result) {
                        mBinding.refreshLayout.finishLoadMore();
                        mBinding.refreshLayout.finishRefresh();
                        Log.d(TAG, "onSucceed() called with: result = [" + result.getMessage() + "]");
                        data = result.getData();
                        if (data == null) {
                            return;
                        }
                        boolean isOnline = data.isOnline;
                        if (isOnline) {
                            mBinding.status.setText("【在线】");
                            mBinding.status.setTextColor(Color.parseColor("#ff00BC77"));
                        } else {
                            mBinding.status.setTextColor(Color.parseColor("#ff0ed3ea"));
                            mBinding.status.setText("【离线】");
                        }
                        List<ChatGetApi.Chats> chats = data.chats;
                        if (chats != null && chats.size() > 0) {
                            lastId = chats.get(chats.size() - 1).id;
                            Collections.reverse(data.chats);
                            if (refresh) {
                                adapter.setData(data.chats);
                            } else {
                                adapter.addData(data.chats);
                            }
                            List list = adapter.getData();
                            mBinding.recyclerView.scrollToPosition(list.size() - 1);
                        }
                    }
                });
    }


    public void back(View view) {
        finish();
    }


    public void getPic(View view) {
        XXPermissions.with(this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        selectPic();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.showShort("获取存储权限失败");
                    }
                });
    }

    private void selectPic() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (LocalMedia media : result) {
                            Luban.with(mActivity)
                                    .load(media.getRealPath())
                                    .ignoreBy(50)
                                    .setTargetDir(CreateFileUtils.getSandboxPath(mActivity))
                                    .setCompressListener(new OnCompressListener() {
                                                             @Override
                                                             public void onStart() {
                                                             }

                                                             @Override
                                                             public void onSuccess(int index, File compressFile) {
                                                                 uploadPic(compressFile);
                                                             }

                                                             @Override
                                                             public void onError(int index, Throwable e) {
                                                             }
                                                         }
                                    ).launch();
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void uploadPic(File compressFile) {
        EasyHttp.post(mActivity).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(compressFile)
                        .setWatermark(true))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        UpdateImageApi.Bean bean = result.getData();
                        if (bean == null) {
                            return;
                        }
                        String url = bean.getUrl();
                        if (TextUtils.isEmpty(url)) {
                            return;
                        }
                        send(url);
                    }
                });
    }

    private void send(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        EasyHttp.post(mActivity).api(new ChatSendApi().setContent(url).setReceiveUserId(userId))
                .request(new HttpCallback<HttpData<ChatSendApi.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<ChatSendApi.Bean> result) {
                        if (result.getCode() == 1) {
                            ToastUtils.showShort("发送成功");
                            mBinding.msg.setText("");
                            getData(true);
                            EventBus.getDefault().post(new LoginStateEvent(1));
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatPayEvent(List<HeartBeatRequest.NewChat> event) {
        for (HeartBeatRequest.NewChat newChat : event) {
            if (newChat.userId.equals(userId) && newChat.unreadCount > 0) {
                getData(true);
                break;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    // 重写onActivityResult方法来获取返回的图片

    public void send(View view) {
        send(mBinding.msg.getText().toString().trim());
    }

    public void close(View view) {
        mBinding.tips.setVisibility(View.GONE);
    }

}